const mongoose = require('mongoose');
require('dotenv').config();

const connectDB = async () => {
  try {
    // 解析连接字符串以获取认证信息
const mongoUri = process.env.MONGODB_URI;
const conn = await mongoose.connect(mongoUri, {
      useNewUrlParser: true,
      serverSelectionTimeoutMS: 30000, // 延长超时到30秒
      socketTimeoutMS: 45000,          // socket超时设置
      authSource: 'admin',            // 明确指定认证源
    });

    console.log(`MongoDB Connected: ${conn.connection.host}`);
  } catch (error) {
    console.error(`Error: ${error.message}`);
    process.exit(1);
  }
};

module.exports = connectDB;